import 'package:dio/dio.dart';
import 'package:f_enjoy_plus/utils/eventBus.dart';
import 'package:f_enjoy_plus/utils/loading.dart';
import 'package:f_enjoy_plus/utils/toast.dart';
import 'package:f_enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';

class Http {
  /// 单例模式
  final Dio _dio = Dio();

  Http() {
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    _dio.options.connectTimeout = Duration(seconds: 10);
    _dio.options.receiveTimeout = Duration(seconds: 30);
    _dio.options.headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };

    _initInterceptors();
  }

  /// 添加拦截器
  void _initInterceptors() {
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          final token = TokenManager.instance.getToken() ?? '';
          if (token.isNotEmpty) {
            options.headers['Authorization'] = 'Bearer $token';
          }
          return handler.next(options);
        },
        onResponse: (response, handler) {
          return handler.next(response);
        },
        onError: (error, handler) {
          return handler.next(error);
        },
      ),
    );
  }

  dynamic _handleResponse(Response response, {bool returnFullResponse = false}) {
    print('HTTP状态码: ${response.statusCode}');
    print('响应数据: ${response.data}');
    
    if (response.statusCode == 200) {
      if (returnFullResponse) {
        return response.data;
      }
      // 检查API返回的业务状态码
      if (response.data['code'] == 10000) {
        return response.data['data'];
      } else {
        ToastUtils.error(response.data['message']);
        // 处理业务逻辑错误
        throw Exception('业务错误: ${response.data['message']}');
      }
    } else {
      throw Exception('HTTP请求失败: ${response.statusCode}');
    }
  }

  void _handleError(DioException error) {
    if (error.response?.statusCode == 401) {
      TokenManager.instance.clearToken();
      eventBus.fire(LogoutEvent());
      throw Exception('登录过期');
    } else {
      throw Exception('请求失败: ${error.response?.statusCode ?? error.message}');
    }
  }

  /// get请求
  Future<dynamic> get(
    String url, {
    Map<String, dynamic>? params,
    bool returnFullResponse = false,
    bool showLoading = false,
  }) async {
    try {
      if (showLoading) LoadingUtils.show();
      final response = await _dio.get(url, queryParameters: params);
      return _handleResponse(response, returnFullResponse: returnFullResponse);
    } on DioException catch (error) {
      _handleError(error);
      rethrow; // 确保错误继续传播
    } catch (e) {
      throw Exception('未知错误: $e');
    } finally {
      if (showLoading) LoadingUtils.hide();
    }
  }

  /// post请求
  Future<dynamic> post(
    String url, 
    dynamic data, {
    bool returnFullResponse = false,
    bool showLoading = true,
  }) async {
    try {
      if (showLoading) LoadingUtils.show();
      final response = await _dio.post(url, data: data);
      return _handleResponse(response, returnFullResponse: returnFullResponse);
    } on DioException catch (error) {
      _handleError(error);
      rethrow;
    } catch (e) {
      throw Exception('未知错误: $e');
    } finally {
      if (showLoading) LoadingUtils.hide();
    }
  }

  /// put请求
  Future<dynamic> put(
    String url, {
    dynamic data,
    bool returnFullResponse = false,
    bool showLoading = false,
  }) async {
    try {
      if (showLoading) LoadingUtils.show();
      final response = await _dio.put(url, data: data);
      return _handleResponse(response, returnFullResponse: returnFullResponse);
    } on DioException catch (error) {
      _handleError(error);
      rethrow;
    } catch (e) {
      throw Exception('未知错误: $e');
    } finally {
      if (showLoading) LoadingUtils.hide();
    }
  }

  /// delete请求
  Future<dynamic> delete(
    String url, {
    dynamic data,
    bool returnFullResponse = false,
    bool showLoading = false,
  }) async {
    try {
      if (showLoading) LoadingUtils.show();
      final response = await _dio.delete(url, data: data);
      return _handleResponse(response, returnFullResponse: returnFullResponse);
    } on DioException catch (error) {
      _handleError(error);
      rethrow;
    } catch (e) {
      throw Exception('未知错误: $e');
    } finally {
      if (showLoading) LoadingUtils.hide();
    }
  }
}

/// 导出
final http = Http();
